<script setup lang="ts">
import { ref, shallowRef, onBeforeMount, nextTick } from 'vue'
import { useTableMixin } from '@/hooks/useTableMixin'
import { ElMessage as message } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import Add from './add.vue'
import Update from './update.vue'
import AddCategory from './addCategory.vue'
import UpdateCategory from './updateCategory.vue'
import { setTableHeight } from '@/common/utils'
import { actionKeys } from '@/common/config'
import { primaryColor_hex } from '@/theme/config'
import {
	getDictionaryCategoryPageApi,
	getDictionaryCategoryListApi,
	deleteDictionaryCategoryApi,
	getDictionaryPageApi,
	deleteDictionaryApi,
	getSuccessStatus,
} from '@/api/dictionary'

// 小于8列不建议每列都写列宽，写了可能导致撑不满布局100%。不写列宽表示自适应，自动补填剩余空间
const columns = shallowRef<TableColConfig[]>([
	{
		label: '复选框列',
		prop: 'selection',
		columnKey: 'selection',
		type: 'selection',
		// width: 55,
		fixed: 'left',
		align: 'center',
	},
	{
		label: '字典类别',
		prop: 'categoryName',
		columnKey: 'categoryName',
		// width: 120,
		align: 'center',
		showOverflowTooltip:true,
	},
	{
		label: '名称',
		prop: 'name',
		columnKey: 'name',
		// width: 120,
		align: 'center',
	},
	{
		label: '值',
		prop: 'value',
		columnKey: 'value',
		// width: 120,
		align: 'center',
	},
	{
		label: '操作',
		prop: 'operation',
		columnKey: 'operation',
		fixed: 'right',
		resizable: false,
		align: 'center',
		// width: 125,
	},
])

const addCategoryDialogVisible = ref(false)
const updateCategoryDialogVisible = ref(false)
const categoryList = ref<DictionaryCategoryType[]>([])
const editCategory = ref({} as DictionaryCategoryType)
const addCategoryRef = ref()
const updateCategoryRef = ref()
const searchDictionaryCategoryKeyword = ref('')
const activeCategoryKey = ref('')
const leftListHeight = ref<number>()
const noOpearteCategorys=['requestAuth']
const isDisabled=(item:{categoryName:string,[key:string]:any})=>noOpearteCategorys.includes(item.categoryName)

const searchOptions = ref<SearchOptionType[]>([
	{ type: 'input', id: 'categoryName', props: { label: '字典类别' } },
	{ type: 'input', id: 'name', props: { label: '字典名称' } },
	{ type: 'input', id: 'value', props: { label: '字典值' } },
])

const {
	basicPaginationConfig, // 表格分页基础配置
	tableRef, // 表格ref
	current, // 当前页码
	size, // 页尺寸
	total, // 总条数
	addRef, // 新增组件ref
	updateRef, // 更新组件ref
	detailRef, // 详情组件ref
	filterOptions, // 查询条件
	getData, // 获取页数据的方法
	tableHeight, // 表格高度
	addDialogVisible, //新增对话框显示隐藏状态
	updateDialogVisible, //更新对话框显示隐藏状态
	tableList, // 表格数据
	selectedRows, // 选中行数据
	editRow, // 当前编辑数据
	addDialogIsFull, // 新增对话框是否全屏的状态
	updateDialogIsFull, // 更新对话框是否全屏的状态
	detailDialogIsFull, // 详情对话框是否全屏的状态
	fixedColWidth, // 固定列列宽
	handleSearchPanelcollapsed, //search-panel组件的 @collapsed 的处理函数
	handleSearch, // 搜索处理函数
	handleReset, // 重置表格数据处理函数
	handlePaginationChange, // 处理分页器变化处理函数
	handleColumnsChange, // 表头变化组件的处理函数
	handleAdd, // 点击新增按钮回调
	handleUpdate, // 点击更新按钮回调
	handleDelete, // 删除处理函数
	handleSelectedRowChange, // 表格选中行变化的回调
	handleImport, // 导入表格处理函数
	handleExport, // 导出表格数据处理函数
	handleAddCommit, // 新增提交处理函数
	handleUpdateCommit, // 更新提交处理函数
} = useTableMixin<DictionaryType>({
	columns,
	listApiFunc: getDictionaryPageApi,
	deleteApiFunc: deleteDictionaryApi,
	actionList: [actionKeys.update, actionKeys.delete],
	reset_after: () => {
		activeCategoryKey.value = ''
	},
	searchPanelcollapsed_after: (h) => {
		setTableHeight({ tableHeightRef: leftListHeight, otherSectionHeight: h + 52 + 52 + 56, isTable: false })
		//console.log(leftListHeight.value,h)
	},
})

onBeforeMount(() => {
	getDictionaryCategoryList()
})

async function getDictionaryCategoryList(keyword?: string) {
	const res = await getDictionaryCategoryListApi({ categoryTitle: keyword })
	if (res.code == getSuccessStatus()) {
		categoryList.value = res.data
	}
}

function handleSearchDictionaryCategory(value: string) {
	// console.log('hhh',value)
	getDictionaryCategoryList(searchDictionaryCategoryKeyword.value)
}

function bindClickCategoryItem(item: DictionaryCategoryType) {
	//console.log({ ...item })
	activeCategoryKey.value = item.categoryName
	handleSearch({ categoryName: item.categoryName })
}

async function handleDeleteCategory(item: DictionaryCategoryType) {
	const res = await deleteDictionaryCategoryApi([item.id])
	if (res.code == getSuccessStatus()) {
		message.success('删除成功')
		getDictionaryCategoryList()
	}
}

function handleAddCategory() {
	addCategoryDialogVisible.value = true
	nextTick(() => {
		addCategoryRef.value?.init && addCategoryRef.value.init()
	})
}

function handleUpdateCategory(item: DictionaryCategoryType) {
	// if(isDisabled(item)) return
	editCategory.value = item
	updateCategoryDialogVisible.value = true
	nextTick(() => {
		updateCategoryRef.value?.init && updateCategoryRef.value.init()
	})
}

async function handleAddCategoryCommit() {
	const success = await addCategoryRef.value.formCommit()
	if (success) {
		addCategoryDialogVisible.value = false
		message.success('新增字典类别成功')
		getDictionaryCategoryList()
	}
}

async function handleUpdateCategoryCommit() {
	const success = await updateCategoryRef.value.formCommit()
	if (success) {
		updateCategoryDialogVisible.value = false
		message.success('更新字典类别成功')
		getDictionaryCategoryList()
	}
}
</script>

<template>
	<div class="dictionaryManage">
		<search-panel @collapsed="handleSearchPanelcollapsed" @search="handleSearch" @reset="handleReset" :options="searchOptions" />

		<div class="container">
			<div class="left">
				<el-input
					v-model="searchDictionaryCategoryKeyword"
					placeholder="输入关键字查询字典类别"
					@keyup.enter="handleSearchDictionaryCategory"
					@clear="
						() => {
							getDictionaryCategoryList('')
						}
					"
					clearable
					class="category-search-input"
				>
					<!-- @change="handleSearchDictionaryCategory" :prefix-icon="Search"  
					仅 当modelValue 改变后，输入框失去焦点或用户按Enter时触发
				-->
					<template #append>
						<el-button :icon="Search" type="primary" @click="handleSearchDictionaryCategory" />
					</template>
				</el-input>

				<div class="categoryList" :style="{ height: leftListHeight + 'px' }">
					<div :class="{ item: true, active: activeCategoryKey == item.categoryName }" v-for="item in categoryList" :columnKey="item.id" @click="bindClickCategoryItem(item)">
						<span class="name">{{ item.categoryTitle }}</span>
						<div class="operate">
							<el-icon :color="primaryColor_hex" style="margin-right: 20px; cursor: pointer" v-if="$hasAuth([actionKeys.update])" @click.stop="handleUpdateCategory(item)">
								<EditPen/>
							</el-icon>
							<el-popconfirm title="确定要删除吗?"  :disabled="isDisabled(item)" confirm-button-text="确定" cancel-button-text="取消" @confirm="handleDeleteCategory(item)" v-if="$hasAuth([actionKeys.delete])">
								<template #reference>
									<el-icon :color="isDisabled(item)?'#a8a8a8':'#f56c6c'" style="cursor: pointer" @click.stop="() => {}"><Delete /></el-icon>
								</template>
							</el-popconfirm>
						</div>
					</div>
				</div>
			</div>

			<div class="right">
				<div class="my-table-tool">
					<div class="tool-left">
						<el-button type="primary" @click="handleExport" v-if="$hasAuth([actionKeys.export])">导出excel</el-button>
					</div>
					<div class="tool-right">
						<el-button type="primary" @click="handleAddCategory" v-if="$hasAuth([actionKeys.add])">新增字典类别</el-button>
						<el-button type="primary" @click="handleAdd" v-if="$hasAuth([actionKeys.add])">新增字典</el-button>
						<set-table-columns :list="columns" @confirm="handleColumnsChange" />
					</div>
				</div>
				<my-table
					ref="tableRef"
					border
					stripe
					:data="tableList"
					:columns="columns"
					style="width: 100%"
					class="myTable"
					rowKey="id"
					:maxHeight="tableHeight"
					@selection-change="handleSelectedRowChange"
					:pagination="{ ...basicPaginationConfig, current, size, total }"
				>
					<template #operation="{ row }">
						<el-button :disabled="isDisabled(row)" type="primary" size="small" v-if="$hasAuth([actionKeys.update])" @click="handleUpdate(row)">修改</el-button>

						<el-popconfirm title="确定要删除吗?" confirm-button-text="确定" cancel-button-text="取消" @confirm="handleDelete(row)" v-if="$hasAuth([actionKeys.delete])">
							<template #reference><el-button :disabled="isDisabled(row)" type="danger" size="small">删除</el-button></template>
						</el-popconfirm>
					</template>
				</my-table>
			</div>
		</div>

		<el-dialog v-model="addCategoryDialogVisible" title="新增字典类别" width="50%" :Dialog="false" draggable :close-on-click-Dialog="false" align-center>
			<el-scrollbar :maxHeight="$getDialogBodyMaxHeight()">
				<!--  套个div防止无论何时都出现横向滚动 -->
				<div style="padding: 0 10px">
					<AddCategory ref="addCategoryRef" />
				</div>
			</el-scrollbar>
			<template #footer>
				<div class="dialog-footer" style="display: flex; justify-content: flex-end">
					<el-button @click="addCategoryDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleAddCategoryCommit">确定</el-button>
				</div>
			</template>
		</el-dialog>

		<el-dialog v-model="updateCategoryDialogVisible" title="更新字典类别" width="50%" :Dialog="false" draggable :close-on-click-Dialog="false" align-center>
			<el-scrollbar :maxHeight="$getDialogBodyMaxHeight()">
				<div style="padding: 0 10px">
					<UpdateCategory :editRow="editCategory" ref="updateCategoryRef" />
				</div>
			</el-scrollbar>
			<template #footer>
				<div class="dialog-footer" style="display: flex; justify-content: flex-end">
					<el-button @click="updateCategoryDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleUpdateCategoryCommit" :disabled="isDisabled(editCategory)">确定</el-button>
				</div>
			</template>
		</el-dialog>

		<el-dialog v-model="addDialogVisible" title="新增字典" width="80%" :Dialog="false" draggable :close-on-click-Dialog="false" align-center>
			<el-scrollbar :maxHeight="$getDialogBodyMaxHeight()">
				<!--  套个div防止无论何时都出现横向滚动 -->
				<div style="padding: 0 10px">
					<Add :category-list="categoryList" ref="addRef" />
				</div>
			</el-scrollbar>
			<template #footer>
				<div class="dialog-footer" style="display: flex; justify-content: flex-end">
					<el-button @click="addDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleAddCommit">确定</el-button>
				</div>
			</template>
		</el-dialog>

		<el-dialog v-model="updateDialogVisible" title="更新字典" width="80%" :Dialog="false" draggable :close-on-click-Dialog="false" align-center>
			<el-scrollbar :maxHeight="$getDialogBodyMaxHeight()">
				<div style="padding: 0 10px">
					<Update :editRow="editRow" :category-list="categoryList" ref="updateRef" />
				</div>
			</el-scrollbar>
			<template #footer>
				<div class="dialog-footer" style="display: flex; justify-content: flex-end">
					<el-button @click="updateDialogVisible = false">取消</el-button>
					<el-button type="primary" @click="handleUpdateCommit">确定</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<style scoped lang="scss">
.dictionaryManage {
	.container {
		display: flex;
		overflow: hidden;

		.left {
			width: 280px;
			margin: 52px 20px 0 0;

			.category-search-input {
				margin-bottom: 20px;
			}

			.categoryList {
				overflow-y: auto;

				.item {
					display: flex;
					justify-content: space-between;
					padding: 10px 0;
					box-shadow: 3px 6px 6px rgb(251, 247, 247);

					.name {
						font-size: 14px;
					}

					.operate {
						margin-right: 8px;
					}
				}
				.active {
					border-right: 3px solid v-bind(primaryColor_hex);
				}
			}
		}
		.right {
			width: calc(100% - 300px);
		}
	}
}
</style>
